package camp.android.cookbook;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

//TODO: fix the disappearing text fields when we turn the tablet
public class NewRecipe extends Activity{

	private Recipe recipe; //recipe being created/edited 
	private boolean editing; //boolean determining if editing or creating
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_recipe);

		recipe = (Recipe)getIntent().getSerializableExtra("recipe"); 
		editing = recipe != null; //if an intent passed us a recipe, then we are editing
		if(editing)
		{	
			List<Ingredient> ingredients = recipe.getIngredientsList();
			
			EditText title = (EditText) findViewById(R.id.edit_title);
			title.setText(recipe.getTitle()); //allow user to edit the title
			
			EditText description = (EditText) findViewById(R.id.edit_description);
			description.setText(recipe.getSubtitle()); //allow user to edit the description
			
			if(!ingredients.isEmpty())
			{
				//entering the first ingredient and quantity in the default EditTexts
				EditText ingredient1 = (EditText) findViewById(R.id.edit_ingredient1);
				ingredient1.setText(ingredients.get(0).getIngredient()); 
				EditText quantity1 = (EditText) findViewById(R.id.edit_quantity1);
				quantity1.setText(ingredients.get(0).getQuantity());
				for(int i = 1; i < ingredients.size(); i++)
				{
					//adding extra EditTexts for additional ingredients 
					Ingredient now = ingredients.get(i);
					LinearLayout list  = (LinearLayout) findViewById(R.id.outer_recipe_layout);
					addIngredientInput(list, now.getIngredient(), now.getQuantity());
				}
			}	
		}
		Button newIngredient = (Button) findViewById(R.id.addIngredient);
		newIngredient.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) { //add another ingredient by introducing new EditTexts before the plus button
				LinearLayout list = (LinearLayout) findViewById(R.id.outer_recipe_layout);
				addIngredientInput(list, null, null);
			}

		});
		Button next = (Button) findViewById(R.id.continue_procedure);
		next.setOnClickListener(new OnClickListener(){ //grabs text and populates Recipe ingredients when user hits "Next" button
			public void onClick(View v)
			{
				Intent i = new Intent(getApplicationContext(), NewProcedure.class);
				LinearLayout layout = (LinearLayout) findViewById(R.id.outer_recipe_layout);
				String title = (String)(((EditText)layout.getChildAt(1)).getText().toString());
				String subtitle = (String)(((EditText)layout.getChildAt(2)).getText().toString()); //grab title and subtitle fields from form input
				//System.out.println(title + ", " + subtitle);
				List<String> procedure = new ArrayList<String>(); 
				List<String> notes = new ArrayList<String>(); 
				if(editing) //if we're editing, save the procedure and notes for the next page
				{
					procedure = recipe.getProcedureList();
					notes = recipe.getNotesList();
				}	
				Recipe recipe = new Recipe(title, subtitle); //create the Recipe and pass it to our next aActivity
				
				for (int j = 4; j < layout.getChildCount()-1; j++) { //read and store ingredients
					LinearLayout thisRow = (LinearLayout) layout.getChildAt(j);
					String ing = (String)(((EditText)thisRow.getChildAt(0)).getText().toString());
					String quant = (String)(((EditText)thisRow.getChildAt(1)).getText().toString());
					if (ing != null && !ing.equals("")) //&& quant!=null && !quant.equals("")
						recipe.addIngredient(ing, quant);
				}
				if(editing)
				{
					for(String p: procedure)
						recipe.addStep(p);
					for(String n: notes)
						recipe.addNote(n);
				}
				if (!title.equals("")) {
					i.putExtra("recipe", recipe);
					startActivity(i);
				}
			}
		});
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in Action Bar clicked; go home
			Intent intent = new Intent(this, RecipeListView.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	/**
	 * Adds a row in layout containing two EditTexts (can be preloaded) and a delete button
	 * @param layout The layout to be added to
	 * @param defIng Fills the first EditText if not null
	 * @param defQuan Fills the second EditText if not null
	 * @return The row added as a LinearLayout
	 */
	private LinearLayout addIngredientInput(LinearLayout layout, String defIng, String defQuan)
	{
		LinearLayout nextRow = new LinearLayout(getApplicationContext());
		EditText nextIngredient = new EditText(getApplicationContext());
		if(defIng == null)
			nextIngredient.setHint("Ingedient...");
		else
			nextIngredient.setText(defIng);
		EditText nextQuantity = new EditText(getApplicationContext());
		if(defQuan == null)
			nextQuantity.setHint("Quantity...");
		else
			nextQuantity.setText(defQuan);
		Button delete = new Button(getApplicationContext());
		delete.setText("X");
		delete.setOnClickListener(new DeleteOnClickListener());

		nextRow.addView(nextIngredient, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1));
		nextRow.addView(nextQuantity, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 3));
		nextRow.addView(delete, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0));
		layout.addView(nextRow, layout.getChildCount()-1);
		return nextRow;
	}
}
